<template>
  <div class="liveSet">
    <div class="form-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>活动管理</el-breadcrumb-item>
        <el-breadcrumb-item>活动商品订单</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="table-bar">
      <div class="selectBox">
        订单日期：
        <el-date-picker
          style="margin-right: 20px"
          clearable
          v-model="valueTime"
          :picker-options="pickerOptions"
          type="daterange"
          @change="selectTime"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <span>卖场：</span>
        <el-select
          v-model="marketId"
          clearable
          @change="selectMarket"
          filterable
          placeholder="请选择卖场"
        >
          <el-option
            v-for="item in marketList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <span>&nbsp;&nbsp;团队：</span>
        <el-select
          v-model="team_id"
          clearable
          @change="selectTeam"
          filterable
          placeholder="请选择团队"
        >
          <el-option
            v-for="item in teamList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <span>&nbsp;&nbsp;商户：</span>
        <el-select
          v-model="store_id"
          clearable
          @change="selectStore"
          filterable
          placeholder="请选择商户"
        >
          <el-option
            v-for="item in storeList"
            :key="item.id"
            :label="item.store_name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="table-bar">
      <!-- <el-button type="primary" size="medium" @click="handleAdd">添加子活动</el-button> -->
      <div class="selectBox">
        付款状态：
        <el-select
          style="margin-right: 10px"
          clearable
          @change="selectPayStatus"
          v-model="payValue"
          placeholder="请选择"
        >
          <el-option
            v-for="item in payStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        订单状态：
        <el-select
          style="margin-right: 10px"
          clearable
          @change="selectOrderStatus"
          v-model="orderValue"
          placeholder="请选择"
        >
          <el-option
            v-for="item in orderStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        主题活动：
        <el-select
          v-model="activityId"
          multiple
          :multiple-limit="1"
          filterable
          remote
          @change="selectActivity"
          reserve-keyword
          placeholder="请输入活动关键词选择"
          :remote-method="getActivityList"
          :loading="loading"
        >
          <el-option
            v-for="item in activityList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <!-- <el-button
          type="primary"
          style="margin-left: 20px"
          size="medium"
          @click="outFile"
          >导出</el-button
        > -->
        <el-popover
          placement="bottom"
          width="310"
          @hide="hideFN"
          v-model="visible"
        >
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: flex-end;
            "
          >
            从第几条开始导出：<el-input
              style="width: 50%"
              @blur="inputStartNo"
              v-model="start_no"
              placeholder="请输入"
              type="number"
            ></el-input>
          </div>
          <div
            style="
              display: flex;
              align-items: center;
              margin: 10px 0;
              justify-content: flex-end;
            "
          >
            导出数量(最大5000)：<el-input
              style="width: 50%"
              @blur="inputEndNo"
              v-model="end_no"
              placeholder="请输入"
              type="number"
            ></el-input>
          </div>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="visible = false"
              >取消</el-button
            >
            <el-button type="primary" size="mini" @click="outFile"
              >确定</el-button
            >
          </div>
          <el-button
            slot="reference"
            style="margin-left: 20px"
            type="primary"
            size="medium"
            >导出</el-button
          >
        </el-popover>
      </div>
      <div class="inputSearch">
        <el-input
          placeholder="输入订单号，手机号模糊搜索"
          v-model="keyword"
          clearable
          @input="clearInput"
          @keyup.enter.native="searchInput"
        ></el-input>
        <el-button type="primary" size="medium" @click="searchInput"
          >搜索</el-button
        >
      </div>
    </div>
    <div class="partnerList_table">
      <div class="partnerList_bottom_table">
        <table>
          <tr>
            <th></th>
            <th>序号</th>
            <th>团队</th>
            <th>商户</th>
            <th>分享用户</th>
            <th>分享者ID</th>
            <th>购买用户</th>
            <th>购买者ID</th>
            <th>订单ID</th>
            <th>订单总金额</th>
            <th>商品名称(ID)</th>
            <th>订单状态</th>
            <th>支付状态</th>
            <th>支付时间</th>
            <!-- <th>支付金额</th> -->
            <!-- <th>下单时间</th> -->
            <th>礼包是否到账</th>
            <th>所属卖场</th>
            <th>退款状态</th>
            <th>操作</th>
          </tr>
          <tr v-for="(v, i) in tableList" :key="i">
            <td>
              <font
                v-if="v.order_status == 4 && v.pay_status == 1"
                class="checkbox"
                :class="{ check_active: v.checked }"
                @click="handlerCheckbox(i, v.checked)"
                ><i class="el-icon-check"></i
              ></font>
            </td>
            <td>{{ i + 1 + (page - 1) * pageSize }}</td>
            <td>{{ v.team_title }}</td>
            <td>{{ v.store_name }}</td>
            <td>
              <p>{{ v.share_nickname }}</p>
              <p>{{ v.share_mobile }}</p>
            </td>
            <td>{{ v.guide_id }}</td>
            <td>
              <p>{{ v.buy_nickname }}</p>
              <p>{{ v.buy_mobile }}</p>
            </td>
            <td>{{ v.user_id }}</td>
            <td>
              <p>交易单号：{{ v.bill_no }}</p>
              <p>主订单：{{ v.order_id }}</p>
              <p>子订单：{{ v.order_code }}</p>
            </td>
            <td>{{ v.price }}</td>
            <td>{{ v.product_title }}({{ v.product_id }})</td>
            <td>
              {{
                v.order_status == 1
                  ? "待付款"
                  : v.order_status == 2
                  ? "完成"
                  : v.order_status == 5
                  ? "取消"
                  : v.order_status == 4
                  ? "购买成功"
                  : ""
              }}
            </td>
            <td>
              {{
                v.pay_status == 0 ? "未付款" : v.pay_status == 1 ? "已付款" : ""
              }}
            </td>
            <td>
              {{
                v.order_status == 4 && v.pay_status == 1
                  ? $moment(v.pay_time * 1000).format("yyyy-MM-DD HH:mm:ss")
                  : "/"
              }}
            </td>
            <!-- <td>{{v.price}}</td> -->
            <td>
              <span
                v-if="
                  v.order_status == 4 && v.pay_status == 1 && v.order_id_grr
                "
                >是</span
              >
              <span v-else-if="v.order_status != 4 && v.pay_status == 0"
                >/</span
              >
              <span v-else>否</span>
            </td>
            <td>{{ v.market_name }}</td>
            <td>
              {{
                v.refund_status == 0
                  ? "正常"
                  : v.refund_status == 1
                  ? "待退款"
                  : v.refund_status == 2
                  ? "已退款"
                  : v.refund_status == 3
                  ? "拒绝"
                  : ""
              }}
            </td>
            <td>
              <el-button
                v-if="
                  v.order_status == 4 && v.pay_status == 1 && !v.order_id_grr
                "
                type="primary"
                size="small"
                @click="toBuFa(v.order_id)"
                >补发</el-button
              >
              <!-- <el-button v-if="v.order_status==4 && v.pay_status==1" type="success" size="small" @click="toPushUser(v.user_id)">推送</el-button> -->
              <!-- <button class="editor" :class="{'delete':v.status==1}" @click="toChange(v.item_id,v.status)">{{v.status==1?'关闭':'开启'}}</button> -->
              <!-- <button class="yellow" @click="toDel(v.id)">删除</button> -->
              <!-- <button class="shelves" @click="toDetail(v.order_id)">详情</button> -->
            </td>
          </tr>
          <tr v-if="tableList.length == 0">
            <td class="table_title" colspan="20">当前数据空空如也</td>
          </tr>
        </table>
        <div class="partnerList_bottom_page">
          <div class="partnerList_bottom_page_left">
            <div
              class="partnerList_bottom_page_left_checkAll"
              @click="handerCheckAll"
            >
              <font class="checkbox" :class="{ check_active: checkAll }"
                ><i class="el-icon-check"></i
              ></font>
            </div>
            全选
            <!-- <el-button style="margin-left:10px;" @click="selectPushUser" type="primary" size="small">推送</el-button> -->
          </div>
          <div class="partnerList_bottom_page_right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              background
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 选择推送模板对话框 -->
    <el-dialog
      title="选择推送模板"
      :visible.sync="dialogVisible"
      @closed="closedFn"
      @open="openFn"
      width="30%"
    >
      <el-select clearable v-model="pushValue" placeholder="请选择">
        <el-option
          v-if="item.number == 3537"
          v-for="item in pushTemplate"
          :key="item.number"
          :label="item.title"
          :value="item.number"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPush">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      checkAll: false,
      page: 1,
      pageSize: 10,
      total: 0,
      checkBoxAll: [], // 选中的数据
      shelvesAlls: [],
      tableList: [],
      keyword: "",
      code: "",
      activity_id: "", //主活动id
      fatherName: "", //主活动名称
      payStatus: [
        {
          label: "未付款",
          value: 0,
        },
        {
          label: "已付款",
          value: 1,
        },
      ],
      payValue: "",

      orderStatus: [
        {
          label: "待付款",
          value: 1,
        },
        {
          label: "完成",
          value: 4,
        },
        {
          label: "取消",
          value: 5,
        },
      ],
      orderValue: "",

      pushTemplate: [], //推送模板
      pushValue: "", //选择的推送模板
      pushUserId: "", //需要推送的用户id

      dialogVisible: false,
      valueTime: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6;
        },
      },
      loading: false,
      startDate: "",
      endDate: "",
      activityId: "", //活动id
      activityList: [], //活动列表
      code: "",
      marketId: "", //卖场id
      marketList: [],
      teamList: [], //团队列表
      storeList: [], //商户列表
      // 导出弹出框
      visible: false,
      start_no: 1, //从第几条开始导出
      end_no: 1, //导出数量
      team_id: "",
      store_id: "",
    };
  },
  mounted() {
    this.activity_id = this.$route.query.id;
    this.fatherName = this.$route.query.name;
    this.getSetList();
    this.remoteMethod();
    this.getTeamAll();
    this.getStoreAll();
  },
  methods: {
    // 获取卖场列表
    remoteMethod() {
      this.$http.post("/api/root/Market/marketList").then((res) => {
        console.log(res, "卖场列表");
        if (res.code == 1) {
          this.marketList = res.data ? res.data : [];
        }
      });
    },
    // 选择卖场
    selectMarket() {
      this.page = 1;
      this.pageSize = 10;
      this.getSetList();
    },
    //选择团队
    selectTeam() {
      this.page = 1;
      this.pageSize = 10;
      this.getSetList();
    },
    //获取团队列表
    getTeamAll() {
      this.$http.post("/api/root/activity/team/list").then((res) => {
        if (res.code == 1) {
          this.teamList = res.data.teams ? res.data.teams : [];
        }
      });
    },
    //选择团队下的商户
    selectStore() {
      this.page = 1;
      this.pageSize = 10;
      // if(!this.team_id || this.team_id==''){
      // 	this.$message.warning('请先选择团队')
      // 	return;
      // }
      this.getSetList();
    },
    //获取商户列表
    getStoreAll() {
      this.$http.post("/api/root/store/select/all").then((res) => {
        if (res.code == 1) {
          this.storeList = res.data ? res.data : [];
        }
      });
    },
    // 选择时间
    selectTime() {
      this.startDate = this.valueTime
        ? this.$moment(this.valueTime[0]).format("yyyy-MM-DD")
        : "";
      this.endDate = this.valueTime
        ? this.$moment(this.valueTime[1]).format("yyyy-MM-DD")
        : "";
      this.getSetList();
    },

    // 获取活动列表o
    getActivityList(query) {
      console.log(query);
      let params = {
        keyword: query,
        page: this.page,
        pagesize: this.pageSize,
        code: this.code,
        type: 2,
        market_id: this.marketId,
      };
      this.$http.post("/api/root/activity/lists", params).then((res) => {
        console.log(res, "活动列表");
        if (res.code == 1) {
          this.activityList = res.data.data ? res.data.data : [];
          this.total = res.data.count;
        }
      });
    },

    // 选择活动
    selectActivity() {
      console.log(this.activityId);
      this.page = 1;
      this.pageSize = 10;
      this.getSetList();
    },

    // 获取活动商品订单列表o
    getSetList() {
      let params = {
        keyword: this.keyword,
        page: this.page,
        pagesize: this.pageSize,
        pay_status: this.payValue,
        order_status: this.orderValue,
        start_at: this.startDate,
        end_at: this.endDate,
        activity_id: this.activityId.length ? this.activityId[0] : "",
        market_id: this.marketId,
        team_id: this.team_id,
        store_id: this.store_id,
      };
      this.$http.post("/api/root/activity/order/lists", params).then((res) => {
        console.log(res, "活动列表");
        if (res.code == 1) {
          res.data.data.map((item) => {
            item.checked = false;
          });
          this.tableList = res.data.data ? res.data.data : [];
          this.total = res.data.count;
        }
      });
    },

    // 输入验证
    inputStartNo() {
      if (this.start_no * 1 < 1) {
        this.start_no = 1;
        this.$message.warning("最小为第1条开始导出");
      } else if (this.start_no * 1 > this.total * 1) {
        this.start_no = this.total;
        this.$message.warning(`最大为第${this.total}条开始导出`);
      }
    },
    inputEndNo() {
      if (this.end_no * 1 < 1) {
        this.end_no = 1;
        this.$message.warning("最小导出数量为1");
      } else if (this.end_no * 1 > 5000) {
        this.end_no = 5000;
        this.$message.warning("最大导出数量为5000");
      }
    },

    // 导出弹出隐藏
    hideFN() {
      this.start_no = 1;
      this.end_no = 1;
    },
    // 导出按钮
    outFile() {
      if (this.start_no == "") {
        this.$message.warning("请输入从第几条开始导出");
        return;
      }
      if (this.end_no == "") {
        this.$message.warning("请输入导出数量");
        return;
      }
      var a = document.createElement("a");
      let activity_id = this.activityId.length ? this.activityId[0] : "";
      a.setAttribute(
        "href",
        `/api/root/activity/order/export?keyword=${this.keyword}&pay_status=${this.payValue}&order_status=${this.orderValue}&market_id=${this.marketId}&activity_id=${activity_id}&start_at=${this.startDate}&end_at=${this.endDate}&start_no=${this.start_no}&end_no=${this.end_no}`
      );
      a.setAttribute("target", "_blank");
      a.setAttribute("id", "startTelMedicine");
      // 防止反复添加
      if (document.getElementById("startTelMedicine")) {
        document.body.removeChild(document.getElementById("startTelMedicine"));
      }
      document.body.appendChild(a);
      a.click();
    },

    // 获取推送模板
    getPushTemplate() {
      this.$http
        .post("/api/root/activity/wxsubscribe/templates")
        .then((res) => {
          console.log(res, "推送模板");
          if (res.code == 1) {
            this.pushTemplate = res.data ? res.data : [];
          }
        });
    },
    // 推送按钮
    toPushUser(userId) {
      this.pushUserId = userId;
      this.dialogVisible = true;
    },
    // 全选推送
    selectPushUser() {
      let arr = [];
      this.tableList.map((item) => {
        if (item.order_status == 4 && item.pay_status == 1 && item.checked) {
          arr.push(item.user_id);
        }
      });
      if (!arr.length) {
        this.$message.warning("请选择需要推送的用户");
        return;
      }
      let arrUserId = [...new Set(arr)];
      console.log(arrUserId, "去重后userId");
      this.pushUserId = arrUserId.join(",");
      this.dialogVisible = true;
    },

    // 推送弹出框确定
    submitPush() {
      if (!this.pushValue) {
        this.$message.warning("请选择推送模板");
        return;
      }
      let params = {
        number: this.pushValue,
        user_ids: this.pushUserId,
      };
      console.log(params, "推送时数据");
      this.$http
        .post("/api/root/activity/wxsubscribe/push", params)
        .then((res) => {
          console.log(res, "推送结果");
          if (res.code == 1) {
            this.$message.success(res.msg);
            this.dialogVisible = false;
          } else {
            this.$message.warning(res.msg);
          }
        });
    },

    // 打开推送弹出框
    openFn() {
      this.getPushTemplate();
    },

    // 推送弹出框关闭
    closedFn() {
      this.checkAll = false;
      this.pushUserId = "";
      this.pushValue = "";
      this.tableList.map((item) => {
        if (item.order_status == 4 && item.pay_status == 1) {
          item.checked = this.checkAll;
        }
      });
    },

    // 进入详情
    toDetail(orderId) {
      this.$router.push({
        name: "activityGoodsOrderDetail",
        query: { orderId },
      });
    },

    // 选择订单状态
    selectPayStatus() {
      this.page = 1;
      this.pageSize = 10;
      this.getSetList();
    },
    // 选择订单状态
    selectOrderStatus() {
      this.page = 1;
      this.pageSize = 10;
      this.getSetList();
    },

    // 节目列表
    toParty(id) {
      this.$router.push({ name: "partyList", query: { id } });
    },

    // 搜索
    searchInput() {
      // this.$router.push({name:'activityGoodsOrderDetail',query:{}})
      if (this.keyword != "") {
        this.page = 1;
        this.pageSize = 10;
        this.getSetList();
      }
    },
    // 清空输入框
    clearInput() {
      if (this.keyword == "") {
        this.page = 1;
        this.pageSize = 10;
        this.getSetList();
      }
    },

    // 补发奖品
    toBuFa(order_id) {
      this.$http
        .post("/api/root/activity/order/sent", { order_id })
        .then((res) => {
          console.log(res, "补发奖品结果");
          if (res.code == 1) {
            this.$message.success("补发成功");
            this.getSetList();
          } else {
            this.$message.warning(res.msg);
          }
        });
    },

    // 添加活动按钮
    handleAdd() {
      this.$router.push({
        name: "addChildActivity",
        query: { activity_id: this.activity_id },
      });
    },

    // 删除按钮
    toDel(id) {
      this.$confirm("此操作将删除此该活动, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http.post("/api/root/activity/son/del", { id }).then((res) => {
          console.log(res);
          if (res.code == 1) {
            this.getSetList();
            this.$message({
              type: "success",
              message: "删除成功",
            });
          } else {
            this.$message.warning(res.msg);
          }
        });
      });
    },

    // 编辑按钮
    toEdit(id) {
      this.$router.push({
        name: "addChildActivity",
        query: { id, activity_id: this.activity_id },
      });
    },

    // 更改状态
    toChange(id, sta) {
      let params = {
        id,
        status: sta == 1 ? 0 : 1,
      };
      this.$http.post("/api/root/activity/son/status", params).then((res) => {
        console.log(res, "更改状态");
        if (res.code == 1) {
          this.$message.success("更改成功");
          this.getSetList();
        } else {
          this.$message.warning(res.msg);
        }
      });
    },

    // 多选
    handlerCheckbox(i, checked) {
      console.log(i, checked, "-----");
      if (this.tableList[i].checked) {
        this.tableList[i].checked = false;
      } else {
        this.tableList[i].checked = true;
      }
      let checkArr = []; //满足已付款已购买的数据
      let checkArrOk = []; //满足条件并选中的
      this.tableList.map((item) => {
        if (item.order_status == 4 && item.pay_status == 1) {
          checkArr.push(item);
        }
        if (item.order_status == 4 && item.pay_status == 1 && item.checked) {
          checkArrOk.push(item);
        }
      });

      // 是否全选中或没有全选中
      if (checkArr.length == checkArrOk.length) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
      // console.log(check,'000');
      console.log(this.checkAll, "9999");
    },
    // 全选与全不选
    handerCheckAll() {
      this.checkAll = !this.checkAll;
      this.tableList.map((item) => {
        if (item.order_status == 4 && item.pay_status == 1) {
          item.checked = this.checkAll;
        }
      });
    },

    //更改直播配置
    // toChange(id,sta){
    //     let status = sta==0?1:0;
    //     this.$http.post('/api/root/SystemConfig/changeStatus',{id,status}).then(res=>{
    //         console.log(res,'直播配置结果');
    //         if(res.code==1){
    //             this.$message.success('操作成功')
    //             this.getSetList()
    //         }else{
    //             this.$message.warning(res.msg)
    //         }
    //     })
    // },

    handleSizeChange(val) {
      this.page = 1;
      this.pageSize = val;
      this.getSetList();
      this.checkBoxAll = [];
      this.shelvesAlls = [];
      this.checkAll = false;
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getSetList();
      this.checkBoxAll = [];
      this.shelvesAlls = [];
      this.checkAll = false;
    },
  },
};
</script>
<style lang="less" scoped>
@import "index.less";
</style>